<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
        <button class="layui-btn layui-btn-sm" lay-event="excel">导出Excel</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<!-- 引入jquery.js -->
<!--<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>-->
<script src="/jquary/jquery-1.8.3.js"></script>

<script>
    layui.use('table', function(){
        var table = layui.table;

        table.render({
            elem: '#test'
            ,url:'/user/findByPage'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,title: '用户数据表'
            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                limit:2,
                limits:[1,2,3],
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //显示首页
                ,last: false //显示尾页
            }
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true}
                ,{field:'userName', title:'用户名', width:80, edit: 'text',sort: true}
                ,{field:'userPwd', title:'密码', width:80, edit: 'text'}
                ,{field:'userRealname', title:'真实名字', width:80, edit: 'text'}
                ,{field:'userGender', title:'性别', width:40, edit: 'text',sort: true}
                ,{field:'userEmail', title:'邮箱', width:120, edit: 'text'}
                ,{field:'userPhone', title:'电话', width:120,sort: true}
                ,{field:'userId', title:'身份证号',width:120,sort: true}
                ,{field:'userBirthdate', title:'出生日期', width:120, sort: true,templet:"<div>{{layui.util.toDateString(d.userBirthdate,'yyyy-MM-dd')}}</div>"}
                ,{field:'userLock', title:'是否锁定', width:40}
                ,{field:'userAddress', title:'地址', width:120}
                ,{field:'userImage', title:'图片', width:120,templet:"#img"}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
            ]]
            //,page: true
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    // layer.alert(JSON.stringify(data));

                    //-------------批量删除操作-----------
                    //声明一个变量，用来存储id
                    var ids = '';
                    //遍历data获取id &id=1&id=2...
                    for (var i = 0; i < data.length; i++) {
                        ids += "&ids=" + data[i].id;
                    }
                    // layer.alert(ids);

                    //使用ajax进行提交到后台进行处理
                    $.get("user/deleteAll", ids,
                        function(data){
                            // layer.alert("function");
                            if("success" == data){
                                // layer.alert("success");
                                window.location.href="http://localhost:8080/index.html";
                            }
                        });
                    /*$.ajax({
                        type:"get",
                        url:"user/deleteAll",
                        data:{ids},
                        async: true,
                        success:function (result) {
                            if ("success" == result) {
                                window.location.href="http://localhost:8080/index.html";
                            }
                        },
                        dataType: text
                    });*/

                    //-----------------------------------
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
                case 'excel':
                    var data = checkStatus.data;

                    var ids = '';

                    for (var i = 0; i < data.length; i++) {
                        ids += "&ids=" + data[i].id;
                    }

                    $.get("user/excel", ids,
                        function(data){
                            alert(data);
                        });

                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();
                    layer.close(index);

                    //从数据库中删除
                    $.ajax({
                        type: "POST",
                        url: "user/deleteUserById",
                        data: "id="+data.id,
                        success: function(msg){
                            //location.reload();//重新加载当前页面
                            table.reload("test",{});
                        }
                    });

                });
            } else if(obj.event === 'edit'){
                // layer.alert('编辑行：<br>'+ JSON.stringify(data))
                //首先调用的是查询单个的方法
                queryOne(data);
            }
        });
    });
</script>

<script type="text/html" id="img">
    <div><img src="{{d.userImage}}" width="40" height="40" alt="图片"></div>
</script>

<script>
    function queryOne(data) {
        layer.open({
            title: ['修改用户'],
            type: 1,
            content: $("#updateUser").html(), //我要修改的页面
            area: ['600px', '600px'],
            btn: ['提交','取消'],
            //弹出窗口以后的回调函数
            success: function () {
                $("#id").val(data.id);
                $("#userName").val(data.userName);
                $("#userPwd").val(data.userPwd);
                $("#userRealname").val(data.userRealname);
                //性别
                if("男" == data.userGender){
                    $("#userGender").append('<input type="radio" name="sex" value="男" title="男" checked><input type="radio" name="sex" value="女" title="女">')
                }else {
                    $("#userGender").append('<input type="radio" name="sex" value="男" title="男" ><input type="radio" name="sex" value="女" title="女" checked>')
                }
                $("#userEmail").val(data.userEmail);
                $("#userPhone").val(data.userPhone);
                $("#userId").val(data.userId);
                //生日
                $("#userBirthdate").val(layui.util.toDateString(data.userBirthdate,'yyyy-MM-dd'));

                //是否锁定
                if("0" == data.userLock){
                    $("#userLock").append('<option value="0" selected>解锁</option><option value="1">锁定</option>')
                }else {
                    $("#userLock").append('<option value="0">解锁</option><option value="1" selected>锁定</option>')
                }

                $("#userAddress").val(data.userAddress);

                //渲染页面
                layui.form.render();
            },
            //提交调用该函数
            yes: function () {
                $.ajax({
                    type:"post",
                    url:"user/updateUser",
                    data:$("#updateUserForm").serialize(),
                    success:function (result) {
                        location.reload();//重新加载当前页面
                    },
                });
            },
            //取消
            btn2: function () {
                alert("已取消");
            }
        });
    }
</script>

<script type="text/html" id="updateUser">

    <form id="updateUserForm" class="layui-form">
        <!--页面上不显示id，但是需要作为隐藏域传递-->
        <input type="hidden" id="id" name="id">

        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input id="userName" type="text" name="userName" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">用户密码</label>
            <div class="layui-input-block">
                <input id="userPwd" type="password" name="userPwd" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input id="userRealname" type="text" name="userRealname" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">用户性别</label>
            <div class="layui-input-block">
                <div id="userGender"></div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input id="userEmail" type="text" name="userEmail" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-block">
                <input id="userPhone" type="text" name="userPhone" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">身份证号</label>
            <div class="layui-input-block">
                <input id="userId" type="text" name="userId" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">出生日期</label>
            <div class="layui-input-block">
                <input id="userBirthdate" type="date" name="userBirthdate" lay-verify="date" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">是否锁定</label>
            <div class="layui-input-block">
                <select name="userLock" id="userLock">

                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <input id="userAddress" type="text" name="userAddress" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>


    </form>

</script>

<script>
    layui.use(["laydate","form"],function(){
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#userBirthdate', //指定元素
            format:'yyyy-MM-dd',
        });
    });
</script>

</body>
</html>